//
//  ProfileEditViewController.Action
//  App_Profile
//
//  Created by 蒋晨成 on 2022/1/29.
//

import Adaptor
import App_Common
import Center
import Route
import RxCocoa
import RxSwift
import UICore
import UIKit

extension ProfileEditViewController {
    func bind() {
        contentView.listView.ryDataList = viewModel.items
        contentView.listView.reloadData()

        contentView.signoutButton.addTarget(self, action: #selector(signout), for: .touchUpInside)

        viewModel.reloadData.asObservable()
            .subscribe(onNext: { [weak self] _ in
                guard let self = self else { return }
                self.contentView.listView.ryDataList = self.viewModel.items
                self.contentView.listView.reloadData()
            })
            .disposed(by: disposeBag)

        viewModel.avatarSelected.asDriver(onErrorJustReturn: ())
            .drive(onNext: { [weak self] _ in
                self?.avatarClick()
            })
            .disposed(by: disposeBag)

        viewModel.route.asObserver()
            .subscribe(onNext: { pattern in
                Router.open(pattern: pattern)
            })
            .disposed(by: disposeBag)
    }
}

private extension ProfileEditViewController {
    func avatarClick() {
        logger.info("select avatar")
        ImagePicker.alertChoose(from: self) { [weak self] type in
            guard let self = self else { return }
            self.handelImageType(type)
        }
    }

    func handelImageType(_ type: UIImagePickerController.SourceType) {
        switch type {
        case .camera:
            imagePicker.showCamera { _ in false }
        default:
            imagePicker.showPhotoLibrary { _ in false }
        }
    }

    @objc
    func signout() {
        view.makeToastActivity(.center)
        Router.open(pattern: "security/logout")
    }
}

extension ProfileEditViewController: ImagePickerDelegate {
    func didSelect(image: UIImage?) {
        guard let image = image else { return }

        view.makeToastActivity(.center)
        UserCenter.updateAvatar(image.pngData()) { [weak self] result in
            self?.view.hideToastActivity()
            switch result {
            case .failure(let error):
                self?.view.makeToast(error.localizedDescription, position: .center)
            case .success: break
            }
        }
    }
}
